import axios from 'axios'
import { REFRESH_TOKEN_CODE, RELOGIN_TOKEN_CODE } from '@/constants'

import {
    handleAxiosError,
    handleBackendError,
    handleResponseError,
    handleServiceResult,
    transformRequestData
} from '@/utils/service'

import { handleRefreshToken } from './helpers'

import { useMessage } from 'naive-ui'

const message = useMessage()
/**
 * 处理响应头
 * @param headers
 */
function processHeaders(headers) {

}

/**
 * 封装axios请求类
 * @author Soybean<honghuangdc@gmail.com>
 */
export default class CustomAxiosInstance {
    instance

    backendConfig

    isRefreshing

    retryQueues
    /**
     *
     * @param axiosConfig - axios配置
     * @param backendConfig - 后端返回的数据配置
     */
    constructor(
        axiosConfig,
        backendConfig = {
            codeKey: 'code',
            dataKey: 'data',
            msgKey: 'msg',
            successCode: 200
        }
    ) {
        this.backendConfig = backendConfig
        this.instance = axios.create(axiosConfig)
        this.setInterceptor()
        this.isRefreshing = false
        this.retryQueues = []
    }

    /** 设置请求拦截器 */
    setInterceptor() {
        this.instance.interceptors.request.use(
            async (config) => {
                const handleConfig = { ...config }
                if (handleConfig.headers) {
                    // 数据转换
                    const contentType = handleConfig.headers['Content-Type']
                    handleConfig.data = await transformRequestData(
                        handleConfig.data,
                        contentType
                    )

                    //TODO 二开：在这里进行请求头设置
                    // handleConfig.headers[Keys.TOKEN] = localStg.get(Keys.TOKEN) || ''
                    // console.debug('请求url', handleConfig.url)

                    // if (isApp) {
                    //     handleConfig.headers['JBOLTAPI'] = 'true'
                    //     handleConfig.headers[Keys.APPID] = appId
                    // }
                }

                return handleConfig
            },
            (axiosError) => {
                const error = handleAxiosError(axiosError)
                return handleServiceResult(error, null)
            }
        )
        this.instance.interceptors.response.use(
            async (response) => {
                const { status, config: requestConfig, data: resData, headers } = response

                if (status === 200 || status < 300 || status === 304) {
                    if (requestConfig.onResponse) {
                        requestConfig.onResponse(response)
                    }
                    if (requestConfig.skipInterceptor || requestConfig.skipResponseInterceptor) {
                        return { error: null, result: resData }
                    }


                    processHeaders(headers)

                    const { codeKey, msgKey } = this.backendConfig

                    const code = resData[codeKey]
                    const msg = resData[msgKey]
                    console.debug(code)
                    // token到期, 刷新token
                    if (REFRESH_TOKEN_CODE.includes(code)) {
                        // 原始请求
                        const originRequest = new Promise((resolve) => {
                            this.retryQueues.push(() => {
                                resolve(this.instance.request(requestConfig))
                            })
                        })

                        if (!this.isRefreshing) {
                            this.isRefreshing = true
                            const success = await handleRefreshToken()
                            if (success) {
                                this.retryQueues.map((cb) => cb())
                            }
                            this.retryQueues = []
                            this.isRefreshing = false
                        }
                        return originRequest
                    }

                    // token失效, 重新登录
                    if (RELOGIN_TOKEN_CODE.includes(code)) {
                        // const { resetAuthStore } = useAuthStore()
                        // resetAuthStore()
                        return
                    }

                    if (code !== 0) {
                        console.debug('code!=0', resData)
                        const error = handleBackendError(code, msg, requestConfig)
                        return handleServiceResult(error, resData)
                    }
                    // 请求成功

                    console.debug('请求',resData)
                    if (resData.msg && !requestConfig.ignoreMsg) {
                        message?.success(resData.msg)
                    }
                    return handleServiceResult(null, resData)
                }
                console.error('被reject')
                // 请求失败
                const error = handleResponseError(response)
                return handleServiceResult(error, null)
            },
            (axiosError) => {
                const error = handleAxiosError(axiosError)
                return handleServiceResult(error, null)
            }
        )
    }
}
